const app=getApp()
Page({
    data:({
    userInfo:'',
    openid:'',
    }),
    onShow:function(){
    let user = wx.getStorageSync('user')
    console.log('进入小程序的页面的缓存',user)
    this.setData({
        userInfo:user
    })
    },
    //授权登录
    login(){
        let that=this
        wx.getUserProfile({
            desc:'必须授权后才能使用',
            success:res=>{
                var currentTime=new Date(parseInt(Date.parse(new Date()))).toLocaleString().replace(/:\d  {1,2}$/,' ');
                let user=res.userInfo
                //检查是否之前授权登陆过
                wx.cloud.database().collection('login_users').where({
                    _openid:wx.getStorageSync('openid')
                }).get({
                    success(res){
                        if(res.data.length==0){
                            console.log(currentTime);
                            wx.cloud.database().collection('login_users').add({
                                data:{
                                    touxiang:user.avatarUrl,
                                    nickName:user.nickName,
                                    time:currentTime
                                }
                            })
                        }else{
                            console.log(res.data[0]._id);
                            var _id=res.data[0]._id
                            wx.cloud.database().collection('login_users').doc(_id).set({
                                data:{
                                    touxiang:user.avatarUrl,
                                    nickName:user.nickName,
                                    time:currentTime
                                }
                            })
                        }
                    }
                })
                
                //把用户信息缓存到本地
                wx.setStorageSync('user',user)
                this.setData({
                    userInfo:user
                })
                wx.showToast({
                    title: '登陆成功',
                    icon:"success",
                    duration:1500
                  })
            },
            fail:res=>{
                wx.showToast({
                    title: '登陆失败',
                    icon:"error",
                    duration:1500
                  })
            }
            
        })
    },
        //退出登录
        logout(){
            this.setData({
                userInfo:'',
            })
            wx.setStorageSync('user','')
        }
    })